package com.chuanke.ckfamily.service.finance.impl;

import com.chuanke.ckfamily.service.common.CacheService;
import com.chuanke.ckfamily.service.common.impl.RedisLockUtil;
import com.chuanke.ckfamily.service.constant.BillStatus;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chuanke.ckfamily.dao.base.CkUtil;
import com.chuanke.ckfamily.dao.finance.BillDao;
import com.chuanke.ckfamily.dao.finance.model.Bill;
import com.chuanke.ckfamily.service.finance.BillService;
import com.chuanke.ckfamily.service.util.CKCRUDBuilder;
import com.weijie.core.BaseBiz;
import com.weijie.core.util.DateUtils;

import java.sql.Timestamp;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class BillServiceImpl extends BaseBiz<Bill, BillDao> implements BillService {
	private static final Logger log = LoggerFactory.getLogger(BillServiceImpl.class);
	@Autowired
	private CacheService cacheService;

	@Override
	public void addBill(Long uid, Long money, int type, Long fansId, String note) {
		Bill bill = new Bill();
		bill.setUid(uid);
		bill.setMoney(money);
		bill.setOptype(type);
		bill.setFans_id(fansId);
		bill.setFlag(BillStatus.UNSUBMIT.getStatus());
		bill.setCreate_time(new Timestamp(System.currentTimeMillis()));
		bill.setFnote(note);
		save(bill);
		cacheService.leftPush(CacheService.KEY_PREFIX.bill_queue.name(), bill);
	}

	@Override
	public void addBill(Long uid, Long money, int type, Timestamp create_time, Long fansId, String note) {
		List<Map<String, Object>> recovery = baseDao.getRecovery(DateUtils.format(create_time), uid, type);
		if (recovery.size() == 0) {
			Bill bill = new Bill();
			bill.setUid(uid);
			bill.setMoney(money);
			bill.setOptype(type);
			bill.setFans_id(fansId);
			bill.setFlag(BillStatus.UNSUBMIT.getStatus());
			bill.setCreate_time(create_time);
			bill.setFnote(note);
			save(bill);
			cacheService.leftPush(CacheService.KEY_PREFIX.bill_queue.name(), bill);
			return;
		}
		log.info("===============================recovery={}", recovery);
	}

	@Override
	public void addBills(List<Bill> bills) {
		baseDao.addList(bills);
		RedisLockUtil redisLock = null;
		try {
			redisLock = cacheService.getLock(CacheService.KEY_PREFIX.bill_queue.name());
			for (Bill bill : bills) {
				cacheService.leftPush(CacheService.KEY_PREFIX.bill_queue.name(), bill);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (redisLock != null) {
				redisLock.unlock();
			}
		}
	}
}